package com.loyal.loyalerp.basedata.company.serviceImpl;


import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.loyal.loyalerp.basedata.company.mapper.GyCompanyMapper;
import com.loyal.loyalerp.basedata.company.model.GyCompany;
import com.loyal.loyalerp.basedata.company.service.CompanyService;
import com.loyal.loyalerp.basedata.department.mapper.DepartmentMapper;
import com.loyal.loyalerp.basedata.department.model.Department;
import com.loyal.loyalerp.humenresource.role.mapper.GyRoleMapper;
import com.loyal.loyalerp.humenresource.role.model.GyRole;
import com.loyal.loyalerp.mapper.GyPersonMapper;
import com.loyal.loyalerp.mapper.GyRolePermissionMapper;
import com.loyal.loyalerp.mapper.GyUserMapper;
import com.loyal.loyalerp.mapper.GyUserRoleMapper;
import com.loyal.loyalerp.model.GyUser;


@Service
public class CompanyServiceImpl implements CompanyService {
	@Autowired
	GyCompanyMapper companyMapper;
	@Autowired
	GyUserRoleMapper userRoleMapper;
	@Autowired
	GyUserMapper userMapper;
	@Autowired
	DepartmentMapper departMentMapper;
	@Autowired
	GyRoleMapper roleMapper;
	@Autowired
	GyPersonMapper personMapper;
	@Autowired
	GyRolePermissionMapper rolePermissionMapper;

	@Override
	public PageInfo<GyCompany> companyList(Integer rows, Integer pageNum, String sord) {
		if (pageNum <= 0)
			return null;
		else {
			Page<GyCompany> page = PageHelper.startPage(pageNum, rows);
			if ("desc".equals(sord))
				companyMapper.companyListDesc();
			else
				companyMapper.companyList();

			return new PageInfo<GyCompany>(page);
		}
	}


	 @Transactional
		@Override
		public void add(GyCompany company) {
			byte flag=1;
			company.setEndflag(flag);//置为末级
	        int i=1;		
			if(company.getParentid()!=0)	  //如果不是顶级公司 得到他的codelevel 以及修改父公司的末级标志
			{			
				GyCompany Parentcompany=company;
				while(true)
				{
					//得到父级公司
					Parentcompany=companyMapper.selectByPrimaryKey(Parentcompany.getParentid());
				    if(Parentcompany!=null) //循环到顶级 即Parentid=0
				    {
				     i++;	
					 if(Parentcompany.getEndflag()==1)//如果是末级,将他置为不是末级
					 {
						 companyMapper.updateEndflagById(Parentcompany.getId());
					 }
				    }	
				    else
				    	break;
				}			
			}	
			company.setCodelevel(i);//插入层级
			companyMapper.insertSelective(company);  //执行插入
		}
	@Transactional
	@Override
	public void delete(Integer id) throws Exception {
					
			GyCompany company=companyMapper.selectByPrimaryKey(id);//得到该公司
		   if(company.getEndflag()==1)//是末级公司，可以删除
		   {
			   try {
				   List<GyUser> users=userMapper.selectByCompanyId(id);
				    for(GyUser user:users)
					{
						userRoleMapper.deleteByUserId(user.getId());//删除用户权限
					   
					}			
					userMapper.deleteByCompanyId(id); //删除用户			
					
					//删除所有的role—permission以及role-user
					List<GyRole> roles=roleMapper.selectByCompanyId(id);
					for(GyRole role:roles)
					{
						rolePermissionMapper.deleteByRoleId(role.getId());
					    userRoleMapper.deleteByRoleId(role.getId());
					
					}					
					roleMapper.deleteByCompanyId(id);//删除角色
				    userRoleMapper.deleteByCompanyId(id);//删除用户角色 多余 但防止其他模块数据错误 防止万一
					List<Department> departments=departMentMapper.selectByCompanyId(id);
					for(Department department:departments)
					{
						personMapper.deleteByDepartmentId(department.getId());//删除部门外键
					}
					personMapper.deleteByCompanyId(id);  //删除人员  多余 防止万一
					departMentMapper.deleteByCompanyId(id);//删除部门
					
				 }
				   catch (Exception e) {
					   throw new RuntimeException("数据库外键删除失败!");
				}
				//所有外键全部删除
			   try
			   {
				companyMapper.deleteByPrimaryKey(id);  //删除公司本体
				//得到父级公司
			    GyCompany Parentcompany=companyMapper.selectByPrimaryKey(company.getParentid());
			    if(Parentcompany!=null)
			    {   
			    int i=companyMapper.countChildren(Parentcompany.getId());//查看该父级公司有没有子集公司
			    if(i<1)//如果没有其他子公司
			    companyMapper.resetEndFlag(Parentcompany.getId());	//将父级公司置为末级公司			  
			    }
			   }
			   catch (Exception e) {
				   e.printStackTrace();
				   throw new RuntimeException("删除失败!");
			}
			   }
		   else//不是末级公司  不可以删除
		   {
			   throw new RuntimeException("该公司不是末级公司 不能删除!");
		   }
	}
   

	@Override
	@Transactional
	public void edit(GyCompany company) {
		
		 int companyId=company.getId();
		 GyCompany oldCompanyInfo=companyMapper.selectByPrimaryKey(companyId);//得到原来的公司信息
		 int oldParentId=oldCompanyInfo.getParentid();
		 int currentParentId=company.getParentid();
		 if(oldParentId==currentParentId)//如果没有修改父级公司			 
		 companyMapper.updateByPrimaryKeySelective(company);//直接修改公司信息
		 else//修改了父级公司
		 {
			 /*
			  * 1.是否将原来的父级公司变成末级公司
			  * 2.将现有父级公司的末级标志置为0(非末级)
			  * 3.得到现有的父级和原来的父级的层级差
			  * 4.将自己包括子公司的层级逐次加上层级差
			  * 5.修改公司信息
			  */
			 changeOldParentCompanyInfo(oldParentId);//如果没有其他子公司就将原来的父级公司置为末级公司
			 companyMapper.updateEndflagById(currentParentId);//将现有父级公司置为非末级
			 int Leveldifference=getLeveldifference(oldParentId,currentParentId);//得到层级差
			 updateLevel(companyId,Leveldifference);//修改该公司以及旗下所有子公司的层级
			 companyMapper.updateByPrimaryKeySelective(company);//修改公司信息
			
		 }
		 
	}
	@Override
	public PageInfo<GyCompany> companySearchList(Integer rows, Integer pageNum, String sord, String searchField,
			String searchString, String searchOper) {
		if (pageNum <= 0)
			return null;
		else {
			
			 Page<GyCompany> page = PageHelper.startPage(pageNum, rows);
			switch(searchField)
			{
			case "CompanyName":{
				companyMapper.companySearchList(searchField,searchString,sord);
				break;}
			case "ParentName":{  
				companyMapper.companySearchListByParentName(searchField,searchString,sord);
				break;}
			default: {return null;}
			}
						
			return new PageInfo<GyCompany>(page);
			}
		
	}

/*
 * 工具方法
 */
	private void updateLevel(int companyId, int leveldifference) {
		GyCompany company =companyMapper.selectByPrimaryKey(companyId);
		List<GyCompany> list=new ArrayList<>();
		list.add(company);
		recursion(list,leveldifference);
	}

	private void recursion(List<GyCompany> list,int leveldifference)
	{
		if(list.size()<=0)
		return;
		List<GyCompany> childrenList=new ArrayList<>();		
	    for(GyCompany company:list)
		{
		   companyMapper.subLevel(company.getId(),leveldifference);//层级更新
		   List<GyCompany> childrens=companyMapper.findChildrens(company.getId());//得到所有孩子
		   childrenList.addAll(childrens);  
		}
	    recursion(childrenList,leveldifference);
	  
	
	}


	private int getLeveldifference(Integer oldParentId, Integer currentParentId) {
		int oldLevel=0;//原来无父级的情况下
		int currentLevel=0;//现在无父级的情况下
		GyCompany oldParentCompany=companyMapper.selectByPrimaryKey(oldParentId);
		GyCompany currentParentCompany=companyMapper.selectByPrimaryKey(currentParentId);
		if(oldParentCompany!=null)
		oldLevel=oldParentCompany.getCodelevel();
		if(currentParentCompany!=null)
		currentLevel=currentParentCompany.getCodelevel();	
		return currentLevel-oldLevel;
		
	}



	private void changeOldParentCompanyInfo(Integer id) {
		int count=companyMapper.countChildren(id);
		if(count<=1) //无其他子公司
		companyMapper.resetEndFlag(id);//置为末级公司
	}



	

	
	
	
	
}
